import { useState, useEffect } from "react";
import { useNavigate, Outlet, useLocation } from "react-router-dom";
import {
  Layout,
  Menu,
  Input,
  List,
  Card,
  Avatar,
  Tag,
  Button,
  Spin,
} from "antd";
import {
  UserOutlined,
  SearchOutlined,
  FireOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import axios from "axios";
import { getAuthToken, setAuthToken } from "@/router";
import "./home.styl";

const { Header, Content, Sider } = Layout;

const menuItems = [
  { key: "/", label: "主页" },
  { key: "/user/profile", label: "个人中心" },
  { key: "/community/bounty", label: "资源悬赏" },
];

export default function Home() {
  const [torrents, setTorrents] = useState([]);
  const [hotList, setHotList] = useState([]);
  const [userData, setUserData] = useState({});
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [torrentsRes, hotRes, userRes] = await Promise.all([
          axios.get("/api/v1/torrent/search?size=10"),
          axios.get("/api/v1/torrent/search?sort=download&size=5"),
          axios.get("/api/v1/user/info", {
            headers: {
              Authorization: `Bearer ${getAuthToken()}`,
            },
          }),
        ]);

        setTorrents(torrentsRes.data?.list || []);
        setHotList(hotRes.data?.list || []);
        setUserData({
          ...userRes.data,
          ratio: Number(userRes.data?.ratio) || 0,
          uploaded: userRes.data?.uploaded || "0 GB",
          downloaded: userRes.data?.downloaded || "0 GB",
        });
      } catch (error) {
        console.error("数据加载失败:", error);
        if (error.response?.status === 401) {
          setAuthToken(null);
          navigate("/login");
        }
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [navigate]);

  const renderUserStats = () => (
    <Card className="user-quickview" title="数据速览">
      <div className="stat-item">
        <label>上传量</label>
        <span>{userData.uploaded}</span>
      </div>
      <div className="stat-item">
        <label>下载量</label>
        <span>{userData.downloaded}</span>
      </div>
      <div className="stat-item">
        <label>分享率</label>
        <Tag color={userData.ratio >= 1 ? "green" : "red"}>
          {userData.ratio.toFixed(2)}
        </Tag>
      </div>
    </Card>
  );

  return (
    <Layout className="home-layout">
      <Header className="header">
        <div className="logo">PT Tracker</div>

        <Input.Search
          placeholder="搜索资源..."
          enterButton={<SearchOutlined />}
          className="search-bar"
          onSearch={(value) => navigate(`/search?q=${value}`)}
        />

        {/* <div className="user-actions">
          <Button
            type="primary"
            icon={<PlusOutlined />}
            danger
            onClick={() => navigate("/community/bounty")}
            style={{ marginRight: "16px" }}
          >
            发布资源悬赏
          </Button>
          <Avatar icon={<UserOutlined />} />
          <Button
            type="link"
            onClick={() => navigate("/user/profile")}
            style={{ color: "#fff" }}
          >
            {userData.username}
          </Button>
        </div> */}
      </Header>

      {loading ? (
        <div className="loading-container">
          <Spin size="large" tip="数据加载中..." />
        </div>
      ) : (
        <Layout>
          <Sider width={200} theme="light">
            <Menu
              mode="inline"
              items={menuItems}
              selectedKeys={[location.pathname]}
              onSelect={({ key }) => navigate(key)}
            />
            {renderUserStats()}
          </Sider>

          <Content className="main-content">
            {location.pathname === "/" && (
              <>
                <div className="torrent-section">
                  <h2>
                    <FireOutlined /> 热门下载
                  </h2>
                  <List
                    dataSource={hotList}
                    renderItem={(item) => (
                      <List.Item
                        actions={[
                          <Tag color="blue">{item.category}</Tag>,
                          <span>↑{item.seeders}</span>,
                        ]}
                      >
                        <List.Item.Meta
                          title={
                            <Button
                              type="link"
                              onClick={() => navigate(`/torrent/${item.id}`)}
                            >
                              {item.name}
                            </Button>
                          }
                          description={`大小: ${item.size} • 发布于 ${item.createdAt}`}
                        />
                      </List.Item>
                    )}
                  />
                </div>

                <div className="torrent-section">
                  <h2>最新资源</h2>
                  <div className="torrent-grid">
                    {torrents.map((torrent) => (
                      <Card
                        key={torrent.id}
                        hoverable
                        onClick={() => navigate(`/torrent/${torrent.id}`)}
                        cover={
                          <img
                            alt="cover"
                            src={torrent.cover || "/default-cover.png"}
                            onError={(e) => {
                              e.target.src = "/default-cover.png";
                            }}
                          />
                        }
                      >
                        <Card.Meta
                          title={torrent.name}
                          description={
                            <>
                              <Tag color={torrent.free ? "green" : "gray"}>
                                {torrent.free ? "免费" : "普通"}
                              </Tag>
                              <span>{torrent.size}</span>
                            </>
                          }
                        />
                      </Card>
                    ))}
                  </div>
                </div>
              </>
            )}
            <Outlet />
          </Content>
        </Layout>
      )}
    </Layout>
  );
}
